package com.hcy.app.screen.cap

import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.util.Log
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.webkit.JavascriptInterface
import android.webkit.WebView
import androidx.activity.ComponentActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.focusable
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.gestures.draggable
import androidx.compose.foundation.gestures.rememberDraggableState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ExitToApp
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import com.hcy.app.R
import com.hcy.app.data.GlobalState
import kotlin.math.roundToInt


@Composable
fun Cap_Desk(linkId: String="",sessionId: String=""){
    val uri ="http://14.103.183.219"
    Log.d(TAG,"${uri}/desktop?linkId=${linkId}&sessionId=${sessionId}")
//    var uri = "http://14.103.183.219/desktop?linkId=1935621574736482304&sessionId=1955798336850104320"
    ScreenOrientationLayout("${uri}/desktop?linkId=${linkId}&sessionId=${sessionId}")
}

@Composable
fun ScreenOrientationLayout(uri: String) {
    val context = LocalContext.current
    val configuration = LocalConfiguration.current
    // 焦点
    val focusRequester = remember { FocusRequester() }

    // 1. 监听屏幕方向变化[1,6,8](@ref)
    val isLandscape by remember(configuration) {
        derivedStateOf { configuration.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE }
    }

    // 2. 控制屏幕方向的状态
    var currentOrientation by remember { mutableStateOf(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) }

    // 3. 布局结构
    if (isLandscape) {
        var offsetX by remember { mutableStateOf(0f) }
        var offsetY by remember { mutableStateOf(0f) }
        // 横屏布局：AndroidView 全屏显示[4](@ref)
        Box(modifier = Modifier.fillMaxSize()) {
            WebViewContainer(
                modifier = Modifier.fillMaxSize(),
                uri=uri
            )

            Row(
                modifier = Modifier
                    .offset { IntOffset(offsetX.roundToInt(), offsetY.roundToInt()) }
                    .draggable(
                        orientation = Orientation.Vertical,
                        state = rememberDraggableState { delta ->
                            offsetY += delta
                        }
                    )
                    .draggable(
                        orientation = Orientation.Horizontal,
                        state = rememberDraggableState { delta ->
                            offsetX += delta
                        }
                    )
                    .padding(16.dp)
                    .align(Alignment.TopEnd)
            ) {
                IconButton(onClick = {
                    (context as ComponentActivity).requestedOrientation =
                        ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                    currentOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
                }) {
                    Icon(
                        imageVector = ImageVector.vectorResource(id = R.drawable.re_screen),
                        contentDescription = "翻转屏幕",
                        tint = Color.Yellow,
                        modifier = Modifier.size(20.dp)
                    )
                }
                IconButton(
                    onClick = {
                        Log.d("miao","点击设置")
                    }
                ) {
                    Icon(Icons.Default.Settings, "设置",Modifier.size(20.dp),Color.Yellow)
                }
            }
        }
    } else {
        // 竖屏布局：AndroidView 占上半屏[4](@ref)
        Column(modifier = Modifier.fillMaxSize().systemBarsPadding()) {
            // 上半部分：AndroidView
            WebViewContainer(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
                    .focusRequester(focusRequester) // 关联焦点请求器
                    .focusable(), // 使组件可获取焦点,
                uri =uri
            )

            // 下半部分：控制区域
            Column(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
                    .background(Color.LightGray)
                    .padding(16.dp),
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text("快捷指令:")
                    IconButton(onClick = {
                        (context as ComponentActivity).requestedOrientation =
                            ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                        currentOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
                    }) {
                        Icon(
                            imageVector = ImageVector.vectorResource(id = R.drawable.re_screen),
                            contentDescription = "翻转屏幕",
                            tint = Color.Yellow,
                            modifier = Modifier.size(20.dp)
                        )
                    }
                }
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Text("组合键:")
                    TextButton(onClick = {}) {
                        Text(text = "Ctrl+Alt+Del", fontSize = 16.sp, color = Color.Yellow)
                    }
                    TextButton(onClick = {}) {
                        Text(text = "win", fontSize = 16.sp, color = Color.Yellow)
                    }
                }
                Row {
                    Text("其他应用:")
                }
            }
        }
    }
}

// WebView 容器组件
@Composable
fun WebViewContainer(modifier: Modifier = Modifier,uri: String) {
    AndroidView(
        factory = { context ->
            WebView(context).apply {
                layoutParams = ViewGroup.LayoutParams(
                    MATCH_PARENT,
                    MATCH_PARENT
                )
                settings.javaScriptEnabled = true  // 启用JS（必要）
                // 注册 JavaScript 接口
                if (GlobalState.CapToken!="" ){
                    // js 中可以通过全局变量 const token = window.AndroidToken.getToken(); 获取到token
                    addJavascriptInterface(TokenJsInterface(GlobalState.CapToken), "AndroidToken")
                }
                // 加载示例网页（替换为你的实际网址）
                loadUrl(uri)
            }
        },
        modifier = modifier
    )
}

class TokenJsInterface(private val token: String) {
    @JavascriptInterface
    fun getToken(): String {
        return token
    }
}